//
//  JPEmotionToolBar.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 2016/10/6.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit

enum JPEmotionToolBarButtonType: Int {
    //  最近
    case recent = 1000
    //  default
    case normal = 1001
    //  Emoji
    case emoji = 1002
    //  浪小花
    case smallFlower = 1003
}

@available(iOS 9.0, *)
class JPEmotionToolBar: UIStackView {
    
    //  最后一个被选中的按钮
    private lazy var lastSelectedButton: UIButton = UIButton()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    //  点击按钮执行的闭包
    var toolBarCallBack: ((JPEmotionToolBarButtonType) -> ())?
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupUI() {
        axis = .horizontal
        distribution = .fillEqually
        
        addButton(title: "最近", imageName: "compose_emotion_table_left", type: .recent)
        addButton(title: "默认", imageName: "compose_emotion_table_mid", type: .normal)
        addButton(title: "Emoji", imageName: "compose_emotion_table_mid", type: .emoji)
        addButton(title: "浪小花", imageName: "compose_emotion_table_right", type: .smallFlower)
    }
    
    func addButton(title: String, imageName: String, type: JPEmotionToolBarButtonType) {
        let button = UIButton()
        button.tag = type.rawValue
        button.setBackgroundImage(UIImage.init(named: imageName + "_normal"), for: .normal)
        button.setBackgroundImage(UIImage.init(named: imageName + "_selected"), for: .selected)
        button.setTitle(title, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.lightGray, for: .selected)
        button.addTarget(self, action: #selector(clickAction(btn:)), for: .touchUpInside)
        button.adjustsImageWhenHighlighted = false
        
        addArrangedSubview(button)
    }
    
    //  按钮的点击事件
    @objc private func clickAction(btn: UIButton) {
        lastSelectedButton.isSelected = false
        btn.isSelected = true
        lastSelectedButton = btn
        
        let type = JPEmotionToolBarButtonType.init(rawValue: btn.tag)
        
        toolBarCallBack!(type!)
    }
    
    func selectedButton(section: Int) {
        
        let button = viewWithTag(section + 1000) as! UIButton
        
        if lastSelectedButton == button {
            return
        }
        print("2")
        lastSelectedButton.isSelected = false
        button.isSelected = true
        lastSelectedButton = button
    }
}
